// src/pages/index.tsx
import type { NextPage } from 'next'
import Head from 'next/head'
import NextLink from "next/link"
import { VStack, Heading, Box, LinkOverlay, LinkBox} from "@chakra-ui/layout"
import { Text, Button } from '@chakra-ui/react'
import { useEffect, useState } from 'react'
import { ethers } from 'ethers'


declare let window:any
const Home: NextPage = () => {
  const [balance, setBalance] = useState<string | undefined>()
  const [currentAccount, setCurrentAccount] = useState<string | undefined>()
  const [chainId, setChainId] = useState<number | undefined>()
  const [chainname, setChainName] = useState<string | undefined>()
  useEffect(() => {
    if(!currentAccount || !ethers.utils.isAddress(currentAccount)){
console.log(777)
return
    } 
    //client side code
    //if(!window.ethereum) return
    
    const provider = new ethers.providers.Web3Provider(window.ethereum)
    console.log("get 余额")
    console.log(currentAccount)
    provider.getBalance(currentAccount).then((result)=>{
      
      setBalance(ethers.utils.formatEther(result))
    })
    provider.getNetwork().then((result)=>{
      setChainId(result.chainId)
      console.log("info")
      console.log(result)
      setChainName(result.name)
    })

  },[currentAccount])

  const onClickConnect=()=>{
    console.log('connect')
    if(!window.ethereum) {
      console.log("please install MetaMask")
      return
    }
    const provider = new ethers.providers.Web3Provider(window.ethereum)

    // MetaMask requires requesting permission to connect users accounts
    provider.send("eth_requestAccounts", [])
    .then((accounts)=>{
      console.log(accounts)
      if(accounts.length>0) setCurrentAccount(accounts[0])
    })
    .catch((e)=>console.log(e))
  
  }

  const onClickDisconnect=()=>{
    console.log('connect')
   setBalance(undefined)
   setCurrentAccount(undefined)
  
  }

  return (
    <>
      <Head>
        <title>My DAPP</title>
      </Head>

      <Heading as="h3"  my={4}>Explore Web3</Heading>          
      <VStack>
        <Box  my={4} p={4} w='100%' borderWidth="1px" borderRadius="lg">
          {currentAccount
          ?<Button type='button' w='100%' onClick={onClickDisconnect}>账户:{currentAccount}</Button>:
          <Button type='button' w='100%' onClick={onClickConnect}>连接:{currentAccount}</Button>
         
        }
        </Box>

       
        {currentAccount
          ? <Box  my={4} p={4} w='100%' borderWidth="1px" borderRadius="lg">
   
         
         <Text>当前余额：{balance}</Text>
         <Text>链ID{chainId} 名字{chainname}</Text></Box>:<></>
        }
        

        <LinkBox  my={4} p={4} w='100%' borderWidth="1px" borderRadius="lg">
          <NextLink href="https://github.com/NoahZinsmeister/web3-react/tree/v6" passHref>
          <LinkOverlay>
            <Heading my={4} fontSize='xl'>Task 3 with link</Heading>
            <Text>Read docs of Web3-React V6</Text>
          </LinkOverlay>
          </NextLink>
        </LinkBox>
      </VStack>
    </>
  )
}

export default Home